<template>
  <el-dialog
    :title="state.title"
    @close="handleClose"
    width="600"
    v-model="state.visible"
    :before-close="beforeClose"
    :loading="state.loading"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <el-form label-width="150px" :model="form" :rules="rules" ref="formRef">
      <el-row>
        <el-col :span="22">
          <el-form-item :label="t('business.pmsc.stationId')" prop="stationId">
            <el-select clearable style="width: 100%" v-model="form.stationId" :placeholder="t('business.pmsc.placeholder.stationId')">
              <el-option v-for="item in stationRefs" :key="item.id" :label="`${item.name[appStore.appLanguage]}`" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('business.pmsc.direct')" prop="direct">
            <el-radio-group v-model="form.direct">
              <el-radio label="In">{{t('business.pmsc.directIn')}}</el-radio>
              <el-radio label="Out">{{t('business.pmsc.directOut')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose" :loading="state.loading">{{t('crud.cancelText')}}</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="state.loading">{{t('crud.confirmText')}}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import { bindStation } from '@/api/business/pmsc'
import {FormInstance, FormRules} from 'element-plus'
import {useI18n} from 'vue-i18n'
import useAppStore from '@/store/modules/app'

const appStore = useAppStore()

const { t } = useI18n()

const emits = defineEmits(['success'])

const formRef = ref<FormInstance>()

const pmsc = ref<any[]>([])
const stationRefs = ref<any[]>([])

const state = reactive({
  visible: false,
  loading: false,
  title: t('business.pmsc.action.bindStation'),
})

const form = ref<any>({
  stationId: '',
  id: '',
  direct: '',
})

const rules = reactive<FormRules>({})

const openDialog = (stations:any[], row?: any) => {
  state.visible = true
  stationRefs.value = stations
  pmsc.value = row
  form.value.id = row.id
  form.value.direct = row.direct
  form.value.stationId = row.stationId
}

const handleClose = () => {
  state.visible = false
}
const handleSubmit = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      state.loading = true
      let params = form.value
      await bindStation(params).finally(() => (state.loading = false))
      ElMessage.success(t('operate.tooltip.success'))
      handleClose()
      emits('success', params)
    }
  })
}

const beforeClose = (done: () => void) => {
  done()
}
defineExpose({
  openDialog,
})
</script>
